using System;
using System.IO;
using System.Web;

namespace SystemFrameworks.Util
{
	/// <summary>
	/// Summary description for Downloader.
	/// </summary>
	public sealed class Downloader
	{
		private Downloader()
		{
		}

		private const string HTTP_HEAD_NAME		= "Content-Disposition";
		private const string HTTP_HEAD_VALUE	= "attachment;filename={0}";		

		/// <summary>
		/// Load file
		/// </summary>
		/// <param name="fileName">For Hearder</param>
		/// <param name="fileContent"></param>
		public static void LoadFile( string fileName, byte[] fileContent )
		{
			HttpResponse response = HttpContext.Current.Response;			
			string httpHeadValue = string.Format( HTTP_HEAD_VALUE, fileName );	
			
			response.ClearHeaders();	
			response.AddHeader( HTTP_HEAD_NAME, httpHeadValue );
			response.BinaryWrite( fileContent );	
			response.End();
		}

		/// <summary>
		/// Export file -	First read file by specified full file name into Byte[],
		///					and then deal with the file,
		///					at last write it to Response
		/// </summary>
		/// <param name="fullName"></param>
		public static void ExportFile( string fullName, bool delete )
		{
			string fileName = Path.GetFileName( fullName );
			byte[] bytes = ReadFile( fullName );
			if ( delete )
			{
				File.Delete( fullName );
			}
			LoadFile( fileName, bytes );
		}
		

		/// <summary>
		/// Export file -	First read file by specified full file name into Byte[],
		///					and then delete it,
		///					at last write it to Response
		/// </summary>
		/// <param name="fullName"></param>
		public static void ExportFile( string fullName )
		{
			ExportFile( fullName, true );
		}

		/// <summary>
		/// Read file to Byte[]
		/// </summary>
		/// <returns></returns>
		public static byte[] ReadFile( string fullName )
		{
			byte[] bytes = null;

			if ( fullName.Trim().Length > 0 )
			{
				FileStream fileStream = new FileStream( fullName, FileMode.Open, FileAccess.Read, FileShare.Read );	
				long length = fileStream.Length;
				bytes = new byte[ length ];
				if ( length > 0 )
				{
					const int BUFFER	= 1024;
					int startIndex		= 0;
					int retval			= 0;
					int count			= BUFFER;
					byte[] buffer = new byte[ BUFFER ];

					do
					{
						if ( startIndex + BUFFER > length )
						{
							count = ( int )(length % BUFFER) ;
						}
						else
						{
							count = BUFFER;
						}

						retval = fileStream.Read( bytes, startIndex, count );
						startIndex += BUFFER;
					}
					while( retval == BUFFER );
				}				
				fileStream.Close();
			}

			return bytes;
		}
	}
}
